/*
 * Parser.cpp
 * This file is part of Dragon and Weed 2 
 *
 * Copyright (C) 2011 - François Berder, Syméon Malengreau
 *
 * Dragon and Weed 2 is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * Dragon and Weed 2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */


// Headers
#include <fstream> 
#include "Path.hpp"
#include "Parser.hpp"
#include "Logger.hpp"
#include "ConvertType.hpp"


/* This function reads a json file and returns the root.
 *	param fileName : name of the file to parse.
 *  param object : the root of the file
 *	return true if the file is parsed with success.
 */
bool Parser::parse(const std::string &fileName, json::Object &root)
{
	// check validity of the file name given
	Path p(fileName);
	if(!p.isValid())
	{
		LogErr << "This file is invalid :" << fileName << '.' << LogEnd;
		return false; 
	}

	// open file
	std::ifstream file(fileName.c_str(), std::ios::in);

	if(!file.is_open())
	{
		LogErr << "Error while opening file :" << fileName << '.' << LogEnd;
		return false;
	}

	else
	{
		// we parse the file
		try {
			json::Reader::Read(root,file);
			file.close();
		}
	    catch (json::Reader::ScanException& e)
	    { 
			LogErr << "Caught json::ScanException : " << e.what() << ", Line/offset: " << numberToString(e.m_locError.m_nLine + 1) << '/' << numberToString(e.m_locError.m_nLineOffset + 1) << " in file : " << fileName << LogEnd;

			return false;			 
  		}
	    catch (json::Reader::ParseException& e)
	    { 
			LogErr << "Caught json::ScanException : " << e.what() << ", Line/offset of token begin: " << numberToString(e.m_locTokenBegin.m_nLine + 1) << '/' << numberToString(e.m_locTokenBegin.m_nLineOffset + 1) << ", Line/offset of token end: " << numberToString(e.m_locTokenEnd.m_nLine + 1) << '/' << numberToString(e.m_locTokenEnd.m_nLineOffset + 1) << " in file : " << fileName << LogEnd;

			return false;			 
  		}
	}
	LogInfo << fileName <<  " parsed with success." << LogEnd; 
	return true;
}
